package com.bbcare.followup.plat.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.dto.bo.DumpBreastSummaryVO;
import com.bbcare.followup.plat.entity.DumpBreastRecord;
import com.bbcare.followup.plat.entity.PatientContentData;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.service.IDumpBreastRecordService;
import com.bbcare.followup.plat.store.ibatis.IDumpBreastRecordDao;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskContentDAO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 复旦儿科泵乳记录Service业务层处理
 *
 * @author gxl
 * @date 2020-11-03
 */
@Service
public class DumpBreastRecordServiceImpl  implements IDumpBreastRecordService
{
    @Autowired
    private IDumpBreastRecordDao dumpBreastRecordMapper;

    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDao;

    @Autowired
    private IPatientTaskContentDAO PatientContentDao;


    /**
     * 查询复旦儿科泵乳记录
     *
     * @param id 复旦儿科泵乳记录ID
     * @return 复旦儿科泵乳记录
     */
    @Override
    public DumpBreastRecord selectDumpBreastRecordById(String id)
    {
        return dumpBreastRecordMapper.selectDumpBreastRecordById(id);
    }

    /**
     * 查询复旦儿科泵乳记录列表
     *
     * @param params 复旦儿科泵乳记录
     * @return 复旦儿科泵乳记录
     */
    @Override
    public List<DumpBreastRecord> selectDumpBreastRecordList(Map params)
    {
        return dumpBreastRecordMapper.selectDumpBreastRecordList(params);
    }

    /**
     * 新增复旦儿科泵乳记录
     *
     * @param dumpBreastRecord 复旦儿科泵乳记录
     * @return 结果
     */
    @Override
    public int insertDumpBreastRecord(DumpBreastRecord dumpBreastRecord)
    {
        dumpBreastRecord.setCreateTime(new Date());
        dumpBreastRecord.setId(UUID.randomUUID().toString());
        return dumpBreastRecordMapper.insertDumpBreastRecord(dumpBreastRecord);
    }

    /**
     * 修改复旦儿科泵乳记录
     *
     * @param dumpBreastRecord 复旦儿科泵乳记录
     * @return 结果
     */
    @Override
    public int updateDumpBreastRecord(DumpBreastRecord dumpBreastRecord)
    {
        if(dumpBreastRecord.getIsUseDrug()!=null && dumpBreastRecord.getIsUseDrug()==2){
            dumpBreastRecord.setUseDrugRemark("");
        }
        dumpBreastRecord.setUpdateTime(new Date());
        return dumpBreastRecordMapper.updateDumpBreastRecord(dumpBreastRecord);
    }

    /**
     * 批量删除复旦儿科泵乳记录
     *
     * @param ids 需要删除的复旦儿科泵乳记录ID
     * @return 结果
     */
    @Override
    public int deleteDumpBreastRecordByIds(String[] ids)
    {
        return dumpBreastRecordMapper.deleteDumpBreastRecordByIds(ids);
    }

    /**
     * 删除复旦儿科泵乳记录信息
     *
     * @param id 复旦儿科泵乳记录ID
     * @return 结果
     */
    @Override
    public int deleteDumpBreastRecordById(String id)
    {
        return dumpBreastRecordMapper.deleteDumpBreastRecordById(id);
    }

    @Override
    public Integer selectCountDumpBreastRecord(Map params) {
        return dumpBreastRecordMapper.selectCountDumpBreastRecord(params);
    }

    @Override
    public Map<String, Object> selectDumpBreastPatientList(Map params, HttpServletRequest request) {
        HashMap<String, Object> responseMap = MapUtil.newHashMap();
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        Integer currentPage = Integer.parseInt(params.get("currentPage").toString());
        Integer pageSize = Integer.parseInt(params.get("pageSize").toString());
        params.put("tenantId", sessionMap.get("tenantId"));
        //特殊处理
        HashMap<String, Object> param2Map = MapUtil.newHashMap();
        param2Map.put("userStatus","0");
        List<PatientQueueScheme> patientQueueSchemes = null;
        try {
            patientQueueSchemes = patientQueueSchemeDao.selectPatientByCondition(param2Map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(CollUtil.isNotEmpty(patientQueueSchemes)){
            List<String> userIdTempIds = patientQueueSchemes.stream().map(PatientQueueScheme::getUserId).collect(Collectors.toList());
            params.put("notIds",userIdTempIds);
        }

        //现根据条件筛选出用户id
        PageHelper.startPage(currentPage, pageSize);
        List<String> userIds = dumpBreastRecordMapper.getUserIdByConditions(params);
        if (CollUtil.isEmpty(userIds)) {
            responseMap.put("data", result);
            responseMap.put("count", 0);
            return responseMap;
        }
        PageInfo<String> page = new PageInfo<>(userIds);

        List<Map<String, Object>> userInfoList = dumpBreastRecordMapper.selectPatientBaseInfoByUserIds(userIds,params.get("queueId").toString());
        Map<String, List<Map<String, Object>>> userInfoMap = userInfoList.stream().collect(Collectors.groupingBy(e -> e.get("user_id").toString()));
        List<Map<String, String>> user24HourTimesList = dumpBreastRecordMapper.select24HourTimesByUserIds(userIds);
        List<Map<String, String>> user24HourrQuantityList = dumpBreastRecordMapper.select24HourrQuantityByUserIds(userIds);
        Map<String, String> user24HourTimesMap = user24HourTimesList.stream().collect(Collectors.toMap(e -> e.get("patient_id"), e -> String.valueOf(e.get("count"))));
        Map<String, String> user24HourrQuantityMap = user24HourrQuantityList.stream().collect(Collectors.toMap(e -> e.get("patient_id"), e -> String.valueOf(e.get("quantity"))));
        //根据id完善用户信息
        String gender;
        for (String userId : userIds) {
            Map<String, Object> baseInfo = new HashMap<>();
            List<Map<String, Object>> userInfo = userInfoMap.get(userId);
            for (Map map : userInfo) {
                baseInfo.put(map.get("question_id").toString(), map.get("question_answer"));
            }
            baseInfo.put("patientId", userId);
            if (user24HourTimesMap.containsKey(userId)) {
                baseInfo.put("24hourTimes", Integer.valueOf(user24HourTimesMap.get(userId)));
            } else {
                baseInfo.put("24hourTimes", 0);
            }

            if (user24HourrQuantityMap.containsKey(userId)) {
                baseInfo.put("24hourQuantity", Double.valueOf(user24HourrQuantityMap.get(userId)));
            } else {
                baseInfo.put("24hourQuantity", 0);
            }

            gender  = baseInfo.get("Pub1100003").toString();
            if (gender.equalsIgnoreCase("男孩") || gender.equalsIgnoreCase("男") )   {
                baseInfo.put("Pub1100003",    "N");
            } else if (gender.equalsIgnoreCase("女孩") || gender.equalsIgnoreCase("女") )    {
                baseInfo.put("Pub1100003",    "F");
            }

            result.add(baseInfo);
        }

        String patientId,lastPatientId;
        List<DumpBreastRecord> lastDumpTimeList = statLastDumpTime();
        for(Map<String, Object> baseInfo : result)   {
            patientId = baseInfo.get("patientId").toString();
            if (null==patientId)    continue;
            for(DumpBreastRecord lastTime : lastDumpTimeList)   {
                lastPatientId = lastTime.getPatientId();
                if (null==lastPatientId)    continue;;
                if (lastPatientId.equals(patientId)) {
                    baseInfo.put("lastDumpTime", lastTime.getLastDumpTime());
                    break;
                }
            }   //设定每个患者的最后泵乳日期。
            if (!baseInfo.containsKey("Pub12x00008"))    {
                baseInfo.put("Pub12x00008", "");    //没有住院号的患者，填写成空串。
            }
        }

        responseMap.put("data", result);
        responseMap.put("count", page.getTotal());
        return responseMap;
    }


    @Override
    public Integer selectCountDumpBreastPatientList(Map params) {
        return dumpBreastRecordMapper.selectCountDumpBreastPatientList(params);
    }

    @Override
    public Object selectLastDumpRecordById(String patientId) {
        return dumpBreastRecordMapper.selectLastDumpRecordById(patientId);
    }

    /**
     * 根据patientId统计某人的泵乳数据。
     * @param patientId
     * @return
     */
    public List<DumpBreastSummaryVO> statDumpRecordByPatientId(final String patientId) {
        Map params = new HashMap();
        Integer currentPage = 1;
        Integer pageSize = 1000;
        params.put("start",pageSize*(currentPage-1));
        params.put("end",pageSize*currentPage);
        params.put("patientId", patientId);
        //查询某个患者的所有泵乳日志结果。
        List<DumpBreastRecord> dumpList = dumpBreastRecordMapper.selectDumpBreastRecordList(params);
        Date dumpDay;
        String dayStr;
        DumpBreastSummaryVO summary;
        Map<String, DumpBreastSummaryVO> sumMap = new HashMap<>();
        Boolean incFlag;
        for(DumpBreastRecord row : dumpList)   {
            dumpDay = row.getDumpTime();
            incFlag = false;
            //TODO.
            try {
                dayStr = DateUtil.getDate_8(dumpDay);
                if (sumMap.containsKey(dayStr)) {
                    summary = sumMap.get(dayStr);
                } else {
                    summary = new DumpBreastSummaryVO();
                    summary.setDayStr(dayStr);
                    sumMap.put(dayStr, summary);
                }
                summary.addRow(row);
                if (null!=row.getLeftBreastQuantity())  {
                    summary.addBreastQuantity(row.getLeftBreastQuantity());
                    summary.incBreastCount();
                    incFlag = true;
                }
                if (null!=row.getRightBreastQuantity()) {
                    summary.addBreastQuantity(row.getRightBreastQuantity());
                    if (!incFlag)   summary.incBreastCount();
                }   //左泵1次+右泵1次仅算1次。
            } catch (java.text.ParseException pe)  {
                System.err.println(pe);
            }
        }

        List<DumpBreastSummaryVO> retList = new ArrayList<>();
        Set sumSet = sumMap.keySet();
        Iterator it= sumSet.iterator();
        while (it.hasNext())    {
            retList.add(sumMap.get(it.next()));
        }
        //泵乳结果按日统计需要按照泵乳日期降序排列。
        Collections.sort(retList, new Comparator<DumpBreastSummaryVO>() {
            @Override
            public int compare(DumpBreastSummaryVO vo1, DumpBreastSummaryVO vo2) {
                return vo2.getDayStr().compareTo(vo1.getDayStr());
            }
        });

        return retList;
    }

    /**
     * 修改患者的床号。
     * @param userId
     * @param bedNo
     * @return
     */
    @Override
    public int updatePatientNo(final String userId, final String bedNo, final String hospitalNo) throws Exception
    {
        PatientContentData content = new PatientContentData();
        content.setUserId(userId);
        int updateCnt=0;
        //注意：bedNo和hospitalNo可能是NULL。
//        if (!bedNo.isEmpty()) {
        if (StringUtils.isNotBlank(bedNo))  {
            content.setQuestionAnswer(bedNo);
            updateCnt = PatientContentDao.updatePatientBedNo(content);
        }
//        if (!hospitalNo.isEmpty())  {
        if (StringUtils.isNotBlank(hospitalNo)) {
            content.setQuestionAnswer(hospitalNo);
            updateCnt = PatientContentDao.updatePatientHospitalNo(content);
        }
        return updateCnt;
    }

    public List<DumpBreastRecord> statLastDumpTime()    {
        return dumpBreastRecordMapper.statLastDumpTime();
    }
}
